<template>
  <div class="u-p-20">
    <el-card shadow="never">
      <div slot="header">
        <b class="u-f-16">
          <span v-if="objForm.id">编辑</span>
          <span v-else>添加</span>商品
        </b>
        <div class="u-right u-5mt">
          <el-button type="success" size="small" icon="el-icon-document-checked" @click="submitForm('objForm')"
            v-if="hasPerm('goodsEditPost')">提交保存</el-button>
          <el-button size="small" icon="el-icon-back" @click="$router.go(-1)">返回</el-button>
        </div>
      </div>
      <el-form :model="objForm" :rules="rules" ref="objForm" label-width="100px" class="u-form"
        style="max-width: 950px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品分类">
              <el-input v-model="objForm.goods_type_id" style="display: none"></el-input>
              <el-cascader :options="levelTree" @change="handleLevelSelect" placeholder="选择分类" clearable
                :props="levelProps" v-model="level_ids">
                <template slot-scope="{ node, data }">
                  <span>{{ data.name }}</span>
                  <span v-if="!node.isLeaf">
                    ({{ data.children.length }})
                  </span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="导航分类">
              <el-select v-model="objForm.goods_nav_id" placeholder="请选择">
                <el-option label="无导航" :value="0"></el-option>
                <el-option v-for="item in levelNavTree" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品标题">
              <el-input v-model="objForm.goods_title" placeholder="请输入商品标题" maxlength="30" show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="展示标签">
              <el-input v-model="objForm.goods_tag" placeholder="请输入商品展示标签 用 、 分割" maxlength="100" show-word-limit>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品简称">
              <el-input v-model="objForm.goods_title_desc" placeholder="请输入商品简称标题(不超过8个字)" maxlength="8"
                show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运费模板">
              <el-select v-model="objForm.freight_id" placeholder="请选择运费模板">
                <el-option v-for="item in freightTemplate" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品排序">
              <el-input-number v-model="objForm.sort" :min="0" label="数值越大权重越高"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推荐商品">
              <el-switch v-model="objForm.goods_hot_status" active-color="#13ce66" :active-value="2"
                inactive-color="#666" :inactive-value="1"></el-switch>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="8" v-if="objForm.goods_reserve==1">
            <el-form-item label="预售总数">
              <el-input v-model="objForm.goods_reserve_storage" placeholder="请输入预售总数">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10" v-if="objForm.goods_reserve==1">
            <el-form-item label="预售发货时间">
              <el-date-picker v-model="objForm.goods_reserve_send" type="date" value-format="timestamp"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品状态">
          <el-radio v-model="objForm.goods_status" :label="1">已上架</el-radio>
          <el-radio v-model="objForm.goods_status" :label="2">审核通过待上架</el-radio>
          <el-radio v-model="objForm.goods_status" :label="3">审核中</el-radio>
          <el-radio v-model="objForm.goods_status" :label="4">审核失败</el-radio>
        </el-form-item>
        <el-form-item label="商品类型">
          <el-radio v-model="objForm.goods_special" :label="0">普通商品</el-radio>
          <el-radio v-model="objForm.goods_special" :label="3">大礼包</el-radio>
        </el-form-item>
        <el-form-item label="审核备注">
          <el-input v-model="objForm.remark" placeholder="审核备注"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="进货商">
              <el-select v-model="objForm.distributor_id" placeholder="请选择进货商">
                <el-option v-for="item in distributorList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-tabs v-model="activeName">
          <el-tab-pane label="商品规格" name="attr">
            <div class="attr-div">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="添加规格名称">
                    <el-input v-model="specName" placeholder="请输入规格名称" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="3">
                  <el-button type="primary" @click="addAttr" v-if="objForm.attr_list.length<=1">添加</el-button>
                </el-col>
              </el-row>
              <div class="line"></div>
              <el-row :gutter="20" v-for="(item, index) in objForm.attr_list" v-bind:key="index">
                <el-col :span="14">
                  <el-form-item :label="item.name">
                    <el-checkbox v-for="(itemx, indexx) in item.list" v-bind:key="indexx + '_value'"
                      v-model="itemx.selected" @change="selectValue">
                      {{ itemx.name }}
                      <i class="el-icon-close" @click.stop="onDeleteAttrValue(index, indexx)"></i>
                    </el-checkbox>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-input v-model="specValue[index]" size="mini" placeholder="请输入规格值" clearable></el-input>
                    </el-col>
                    <el-col :span="5">
                      <el-button type="primary" size="mini" @click="addValue(item.id, index)">添加</el-button>
                    </el-col>
                    <el-col :span="7">
                      <el-button type="danger" size="mini" @click="onDeleteAttr(index)">删除</el-button>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </div>
            <div class="goods-list">
              <el-table :data="objForm.goods_list" class="u-mt-10" v-viewer>
                <el-table-column label="商品图片" width="100">
                  <template slot-scope="scope">
                    <div @click="uploadImg('uploadGoods' + scope.$index)"
                      style="width: 80px; height: 80px; background-size: 100%" :style="
                        'background-image: url(' + scope.row.goods_image + ')'
                      "></div>
                    <!-- <el-image style="width: 80px; height: 80px;" :src="scope.row.goods_image"  lazy  @click="uploadImg('uploadGoods'+scope.$index)"></el-image> -->
                    <div style="display: none">
                      <upload file-folder="goods_img" list-type="picture-card" :index="scope.$index" :limit="1"
                        accept="image/jpeg, image/png" tips="只能上传jpg/png文件，且不超过4MB"
                        @getUploadFiles="getGoodsUploadFiles"></upload>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="规格名称" prop="attribute_names"></el-table-column>
                <el-table-column label="单位" width="100">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.goods_unit" @input="onInputUnit"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="单价" width="100">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.goods_unit_price" @input="onInputPrice"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="数量" width="100">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.goods_unit_number" @input="onInputNumber(scope.$index)"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="市场价" width="100">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.goods_market_price"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="进货价" width="100">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.goods_cost_price" @input="onInputCostPrice"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="出售价" width="100">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.goods_sell_price"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="库存" width="100">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.goods_storage" @input="onInputStorage"></el-input>
                  </template>
                </el-table-column>
                <!-- <el-table-column label="限购" width="100">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.goods_limit"></el-input>
                  </template>
                </el-table-column> -->
                <el-table-column label="礼包趣豆" width="100" v-if="objForm.goods_special==3">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.bean"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="兑换券" width="100"  v-if="objForm.goods_special==3">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.coupon"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="分成量" width="100">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.goods_ratio_price" @input="onRatioPrice(scope.$index)"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="总利润" width="100">
                  <template slot-scope="scope">
                    <el-tag>{{ scope.row.difference_price }}</el-tag>
                  </template>
                </el-table-column>
                <!-- <el-table-column label="净利润" width="100">
                  <template slot-scope="scope">
                    <el-tag>{{ scope.row.profits_price }}</el-tag>
                  </template>
                </el-table-column> -->
              </el-table>
            </div>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="intro">
            <el-form-item label="封面图片" prop="goods_img">
              <upload file-folder="goods_img" :file-arr="fileList" list-type="picture-card" :limit="1"
                accept="image/jpeg, image/png" tips="只能上传jpg/png文件，且不超过4MB" @getUploadFiles="getUploadFiles"></upload>
            </el-form-item>

            <el-form-item label="相册图片" prop="goods_photo">
              <upload-drag file-folder="goods_photo" :file-arr="fileList1" :multiple="true" list-type="picture-card"
                :limit="10" accept="image/jpeg, image/png" tips="只能上传jpg/png文件，且不超过4MB" @getUploadFiles="goodsPhoto">
              </upload-drag>
            </el-form-item>
            <el-form-item label="商品详情" prop="goods_detail">
              <upload-drag file-folder="goods_detail" :file-arr="fileList2" :multiple="true" list-type="picture-card"
                :limit="31" accept="image/jpeg, image/png" tips="只能上传jpg/png文件，且不超过4MB" @getUploadFiles="goodsDetail">
              </upload-drag>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="属性管理" name="attribute">
            <el-form-item label="属性字段">
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-input v-model="parameterName" placeholder="属性名称" show-word-limit></el-input>
                </el-col>
                <el-col :span="12">
                  <el-input v-model="parameterValue" placeholder="属性值" show-word-limit></el-input>
                </el-col>
                <el-col :span="4">
                  <el-button type="success" @click="addParameter">增加</el-button>
                </el-col>
              </el-row>
              <div>
                <el-table :data="goods_parameter" class="u-mt-10" v-viewer>
                  <el-table-column label="名称" prop="name"></el-table-column>
                  <el-table-column label="属性值" prop="value"></el-table-column>
                  <el-table-column label="操作" width="220">
                    <template slot-scope="scope">
                      <el-button size="mini" type="text" @click="delParameter(scope)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import commonEdit from "@/mixins/common-edit";
import Upload from "@/components/upload/upload";
import { MessageBox } from "element-ui";
import UploadDrag from "@/components/uploaddrag/uploaddrag";
export default {
  components: {
    Upload,
    UploadDrag,
  },
  mixins: [commonEdit],
  data() {
    return {
      activeName: "attr",
      apiName: "goods",
      backRoute: "goodsIndex", //成功跳转地址
      fileList: [], //临时封面
      fileList1: [], //临时相册
      fileList2: [], //详情
      levelTree: [],
      levelNavTree: [], //导航分类
      level_ids: [],
      levelProps: {
        // checkStrictly:true,
        label: "name",
        value: "id",
        children: "children",
      },
      distributorList: [], //进货商列表
      specName: "",
      specValue: [],
      attrList: [],
      attrIdName: {},
      parameterName: "", //商品参数名称
      parameterValue: "", //商品参数值
      objForm: {
        id: "",
        goods_type_id: "", //分类id
        goods_nav_id: "",
        goods_type_name: "", //分类名称--临时
        goods_title: "", //标题
        goods_text: "", //标题
        goods_title_desc: "", //商品简称
        goods_tag: "", //展示标签
        goods_return_agency_money: 0, //代理佣金
        goods_return_money: 0, //用户购买返现
        goods_top_money: 0, //一级推广佣金
        goods_top_top_money: 0, //二级推广佣金
        goods_channel_money: 0, //分享商品佣金
        goods_max_price: 0, //售价单价最大值
        goods_max_unit: "",//售价单价最大值单位
        goods_min_price: 0, //售价单价最小值
        goods_min_unit: "",//售价单价最小值单位
        goods_min_market_price: 0, //最小市场价格
        goods_min_profit: 0, //最低利润
        goods_status: 1, //是否上线
        goods_hot_status: 2, //热门推荐
        goods_recommend: 2, //公司介绍推荐
        goods_reserve: 0,//是否是预售商品
        goods_reserve_storage: 1000,//预售商品总数
        goods_reserve_send: Date.now() + (3600 * 24 * 90) * 1000,//预计发货时间
        goods_img: "", //封面
        goods_photo: "", //相册
        goods_detail: "", //商品详情
        goods_special: 0, //商品类型
        freight_id: 295, //运费模板id
        sort: 0,
        remark: "", //审核备注
        goods_storage: 0, //商品库存
        attr_ids: [], //商品规格名称id
        goods_list: [], //商品规格数据列表
        attr_list: [], //商品规格列表
        goods_parameter: [], //商品属性列表
        is_member: 1, //是否会员可见
        distributor_id: 0, //进货商id
      },
      go_up: 15,//商品上浮价格
      goods_parameter: [], //商品属性列表
      is_type_show: false, //商品分类选择
      freightTemplate: [], //运费模板
      temp_goods_list: [],
      goodsSpecial: [
        {
          label: "正常商品",
          value: 0,
        },
        {
          label: "虚拟会员商品",
          value: 1,
        },
      ],
    };
  },
  methods: {
    delParameter(item) {
      this.goods_parameter.splice(item.$index, 1);
      this.objForm.goods_parameter = this.goods_parameter;
    },
    addParameter() {
      let that = this;
      this.goods_parameter.push({
        name: that.parameterName,
        value: that.parameterValue,
      });
      this.objForm.goods_parameter = this.goods_parameter;
      this.parameterName = "";
      this.parameterValue = "";
    },
    onDeleteAttr(index) {
      this.delAttribute(this.objForm.attr_list[index].id, "attr", index);
    },
    onDeleteAttrValue(index, indexx) {
      this.delAttribute(
        this.objForm.attr_list[index].list[indexx].id,
        "value",
        index,
        indexx
      );
    },
    addAttr() {
      let that = this;
      let is_rep = false; //规格名称是否重复
      this.objForm.attr_list.forEach(function (item) {
        if (item.name == that.specName) {
          is_rep = true;
        }
      });
      if (is_rep) {
        MessageBox({
          title: "提示",
          message: "规格名称已存在,请更换",
          type: "error",
        });
      } else {
        this.addAttribute("", "attr", this.specName, 0);
        this.specName = "";
      }
    },
    addValue(id, index) {
      let that = this;
      let is_rep = false; //规格名称是否重复
      this.objForm.attr_list.forEach(function (item) {
        if (item.list.length > 0) {
          item.list.forEach(function (itemx) {
            if (itemx.name == that.specValue[index]) {
              is_rep = true;
            }
          });
        }
      });
      if (is_rep) {
        MessageBox({
          title: "提示",
          message: "规格值已存在,请更换",
          type: "error",
        });
      } else {
        this.addAttribute(id, "value", this.specValue[index], index);
        this.specValue[index] = "";
      }
    },
    onRatioPrice(index) {
      //分成利润
      // let that = this;
      let goods_item = this.objForm.goods_list[index];
      if (parseInt(goods_item['difference_price']) < parseInt(goods_item['goods_ratio_price'])) {
        this.objForm.goods_list[index]['goods_ratio_price'] = 0;
        MessageBox({
          title: "提示",
          message: "分成量不能大于利润",
          type: "error",
        });
      }
      // console.log(goods_item);
      // this.onUpdateItem();
    },
    onInputCostPrice() {
      let that = this;
      let goods_list = this.objForm.goods_list;
      let goods_list_temp = [];
      goods_list.forEach(function (item) {
        let difference_price =
          parseFloat(item.goods_sell_price) - parseFloat(item.goods_cost_price); //总利润
        let ratio =
          (parseFloat(that.objForm.goods_return_agency_money) +
            parseFloat(that.objForm.goods_return_money) +
            parseFloat(that.objForm.goods_top_money) +
            parseFloat(that.objForm.goods_top_top_money) +
            parseFloat(that.objForm.goods_channel_money)) /
          100;
        let profits_price = difference_price * (1 - ratio); //净利润
        item.difference_price = difference_price.toFixed(2);
         //分成比例
        item.goods_ratio_price = (difference_price*0.8).toFixed(2);
        item.profits_price = profits_price.toFixed(2);
        goods_list_temp.push(item);
      });
      this.objForm.goods_list = goods_list_temp;
    },
    onInputNumber(index) {
      let that = this;
      let goods_list = this.objForm.goods_list;
      this.objForm.goods_list[index].goods_sell_price = (parseFloat(goods_list[index].goods_unit_price) * parseInt(goods_list[index].goods_unit_number)).toFixed(2);
      let difference_price =
        parseFloat(this.objForm.goods_list[index].goods_sell_price) - parseFloat(this.objForm.goods_list[index].goods_cost_price); //总利润
      let ratio =
        (parseFloat(that.objForm.goods_return_agency_money) +
          parseFloat(that.objForm.goods_return_money) +
          parseFloat(that.objForm.goods_top_money) +
          parseFloat(that.objForm.goods_top_top_money) +
          parseFloat(that.objForm.goods_channel_money)) /
        100;
      let profits_price = difference_price * (1 - ratio); //净利润
      this.objForm.goods_list[index].difference_price = difference_price.toFixed(2);
      this.objForm.goods_list[index].goods_ratio_price = (difference_price*0.8).toFixed(2);

      this.objForm.goods_list[index].profits_price = profits_price.toFixed(2);
    },
    onInputPrice() {
      let max = 0;
      let min = 100000000;
      let index_min = 0;
      let index_max = 0;
      let that = this;
      let goods_list = this.objForm.goods_list;
      let goods_list_temp = [];
      goods_list.forEach(function (item, index) {
        if (max < parseFloat(item.goods_unit_price)) {
          max = parseFloat(item.goods_unit_price);
          index_max = index;
        }
        if (min > parseFloat(item.goods_unit_price)) {
          min = parseFloat(item.goods_unit_price);
          index_min = index;
        }
        item.goods_sell_price = (parseFloat(item.goods_unit_price) * parseInt(item.goods_unit_number)).toFixed(2);
        let difference_price =
          parseFloat(item.goods_sell_price) - parseFloat(item.goods_cost_price); //总利润
        let ratio =
          (parseFloat(that.objForm.goods_return_agency_money) +
            parseFloat(that.objForm.goods_return_money) +
            parseFloat(that.objForm.goods_top_money) +
            parseFloat(that.objForm.goods_top_top_money) +
            parseFloat(that.objForm.goods_channel_money)) /
          100;
        let profits_price = difference_price * (1 - ratio); //净利润
        item.difference_price = difference_price.toFixed(2);
        //分成比例
        item.goods_ratio_price = (difference_price*0.8).toFixed(2);
        item.profits_price = profits_price.toFixed(2);
        goods_list_temp.push(item);
      });
      that.objForm.goods_list = goods_list_temp;
      that.objForm.goods_max_price = max;
      that.objForm.goods_max_unit = goods_list[index_max].goods_unit;
      that.objForm.goods_min_price = min;
      that.objForm.goods_min_unit = goods_list[index_min].goods_unit;
      that.objForm.goods_min_market_price =
        that.objForm.goods_list[index_min].goods_market_price;
      that.objForm.goods_min_profit =
        that.objForm.goods_list[index_min].difference_price;
    },
    onInputUnit() {
      this.onUpdateItem();
    },
    onUpdateItem() {
      let max = 0;
      let min = 100000000;
      let index_min = 0;
      let index_max = 0;
      let that = this;
      let goods_list = this.objForm.goods_list;
      let goods_list_temp = [];
      goods_list.forEach(function (item, index) {
        if (max < parseFloat(item.goods_unit_price)) {
          max = parseFloat(item.goods_unit_price);
          index_max = index;
        }
        if (min > parseFloat(item.goods_unit_price)) {
          min = parseFloat(item.goods_unit_price);
          index_min = index;
        }
        let goods_sell_price = (parseFloat(item.goods_unit_price) * parseInt(item.goods_unit_number)).toFixed(2);
        let difference_price =
          parseFloat(goods_sell_price) - parseFloat(item.goods_cost_price); //总利润
        let ratio =
          (parseFloat(that.objForm.goods_return_agency_money) +
            parseFloat(that.objForm.goods_return_money) +
            parseFloat(that.objForm.goods_top_money) +
            parseFloat(that.objForm.goods_top_top_money) +
            parseFloat(that.objForm.goods_channel_money)) /
          100;
        let profits_price = difference_price * (1 - ratio); //净利润

        item.difference_price = difference_price.toFixed(2);
            //分成比例
        item.goods_ratio_price = (difference_price*0.8).toFixed(2);
        item.profits_price = profits_price.toFixed(2);
        goods_list_temp.push(item);
      });
      that.objForm.goods_max_price = max;
      that.objForm.goods_max_unit = goods_list[index_max].goods_unit;
      that.objForm.goods_min_price = min;
      that.objForm.goods_min_unit = goods_list[index_min].goods_unit;
      that.objForm.goods_list = goods_list_temp;
    },
    onInputStorage() {
      let storage = 0;
      this.objForm.goods_list.forEach(function (item) {
        storage += parseInt(item.goods_storage);
      });
      this.objForm.goods_storage = storage;
    },
    selectValue() {
      this.updateSKU();
    },
    delAttribute(id, type, index, indexx = 0) {
      //删除规格名称-规格值
      let that = this;
      this.$api[this.apiName]
        .del_attribute({ id: id, type: type })
        .then((response) => {
          if (response.code == 1) {
            if (type == "attr") {
              this.objForm.attr_list.splice(parseInt(index), 1);
            } else if (type == "value") {
              this.objForm.attr_list[index].list.splice(parseInt(indexx), 1);
            }
            that.updateSKU();
          }
        });
    },
    addAttribute(id, type, name, index = 0) {
      let that = this;
      //添加规格名称--规格值
      this.$api[this.apiName]
        .add_attribute({ id: id, type: type, name: name })
        .then((response) => {
          if (response.code == 1) {
            let id = response.data;
            if (type == "attr") {
              var temp = {
                id: id,
                name: name,
                list: [],
              };
              this.objForm.attr_list.push(temp);
              that.specValue.push("");
            } else if (type == "value") {
              this.objForm.attr_list[parseInt(index)].list.push({
                id: id,
                selected: false,
                name: name,
              });
            }
          }
        });
    },
    getLoadList() {
      let that = this;
      this.$api[this.apiName].load_list().then((response) => {
        if (response.code == 1) {
          that.levelTree = response.data.levelTree;
          that.levelNavTree = response.data.levelNavTree;
          that.freightTemplate = response.data.freightTemplate;
          that.distributorList = response.data.distributorList;
          if (that.objForm.freight_id == 0 || that.objForm.freight_id == "0") {
            that.objForm.freight_id = that.freightTemplate[0].id;
          }
          that.go_up = that.getGoUp(that.objForm.goods_type_id);
        }
      });
    },
    handleLevelSelect(val) {
      if (!(val == null || val == undefined)) {
        this.objForm.goods_type_id = val[val.length - 1];
        this.go_up = this.getGoUp(this.objForm.goods_type_id);

      }
    },
    uploadImg(id) {
      console.log(id);
      document.getElementById(id).click();
      // this.$refs[id].$emit("click");
    },
    getGoodsUploadFiles(files) {
      //规格封面上传回调
      let index = files[0]["index"];
      this.objForm.goods_list[index].goods_image = files[0]["url"];
      // console.log(this.objForm.goods_list);
    },
    getUploadFiles(files) {
      // window.console.log(files);
      //封面上传回调
      this.fileList = files;
      // this.fileList1 = files;
      // this.fileList2 = files;
      this.objForm.goods_img = files[0]["url"];
      // this.objForm.goods_photo = files[0]["url"];
      // this.objForm.goods_detail = files[0]["url"];
    },
    goodsPhoto(files) {
      //相册上传回调
      this.fileList1 = files;
      this.objForm.goods_photo = "";
      for (var i = 0; i < files.length; i++) {
        this.objForm.goods_photo +=
          this.objForm.goods_photo == "" ? files[i].url : "," + files[i].url;
      }
    },
    goodsDetail(files) {
      //详情上传回调
      this.fileList2 = files;
      this.objForm.goods_detail = "";
      for (var i = 0; i < files.length; i++) {
        this.objForm.goods_detail +=
          this.objForm.goods_detail == "" ? files[i].url : "," + files[i].url;
      }
    },
    afterGetInfo() {
      this.level_ids = this.objForm.goods_type_id;
      //初始化-获取编辑数据
      this.fileList = this.objForm.goods_img
        ? [
          {
            url: this.objForm.goods_img,
          },
        ]
        : []; //封面

      this.objForm.goods_photo = this.objForm.goods_photo
        ? this.objForm.goods_photo.split(",")
        : [];
      for (var i = 0; i < this.objForm.goods_photo.length; i++) {
        this.fileList1.push({
          url: this.objForm.goods_photo[i],
        }); //相册
      }

      this.objForm.goods_detail = this.objForm.goods_detail
        ? this.objForm.goods_detail.split(",")
        : [];
      for (var j = 0; j < this.objForm.goods_detail.length; j++) {
        this.fileList2.push({
          url: this.objForm.goods_detail[j],
        }); //详情
      }
      if (this.objForm.goods_reserve_send > 0) {
        this.objForm.goods_reserve_send = this.objForm.goods_reserve_send * 1000;
      }
      this.temp_goods_list = this.objForm.goods_list;
      this.goods_parameter = this.objForm.goods_parameter;
      this.updateSKU();
      this.onUpdateItem();
    },
    /**
     * 转换数据并进行SKU组合
     */
    updateSKU() {
      let that = this;
      let temp_sku = Array();
      let attr_arr_list = {};

      if (this.objForm.attr_list.length <= 0) {
        return;
      }
      that.objForm.attr_ids = [];
      this.objForm.attr_list.forEach(function (item) {
        if (item.list.length > 0) {
          that.objForm.attr_ids.push(item.id);
          item.list.forEach(function (itemx) {
            that.attrIdName[itemx.id] = itemx.name;
            if (itemx.selected) {
              if (attr_arr_list[parseInt(item.id)] == undefined) {
                attr_arr_list[parseInt(item.id)] = [];
              }
              attr_arr_list[parseInt(item.id)].push(itemx.id);
            }
          });
        }
      });
      // console.log(attr_arr_list);
      for (let key in attr_arr_list) {
        temp_sku.push(attr_arr_list[key]);
      }
      if (temp_sku.length <= 0) {
        return;
      }
      // attr_arr_list.forEach(function (item) {
      //   temp_sku.push(item);
      // });
      // console.log(temp_sku);
      let sku = this.doExchange(temp_sku);
      let goodslist = this.getSkuName(sku);
      // console.log(goodslist);

      this.objForm.goods_list = [];
      for (let key in goodslist) {
        let item = this.isInGoods(key);
        let goods_item = null;
        if (item != "") {
          goods_item = item;
        } else {
          goods_item = {
            id: "",
            attribute_ids: key,
            attribute_names: goodslist[key],
            goods_storage: 1000, //库存
            goods_image: "", //视频属性图片
            goods_cost_price: 0, //进货价
            goods_market_price: 0, //市场价
            goods_sell_price: 0, //出售价
            goods_agency_price: 0, //代理价
            difference_price: 0, //总利润
            profits_price: 0, //净利润
            goods_unit_price: 0,//商品规格单价
            goods_ratio_price: 0,//商品分成量
            goods_unit: "",//商品规格单价单位
            goods_unit_number: 0,//商品规格数量
            goods_limit: 0,//限购数量
            bean:0, //礼包包含的趣豆
            coupon:0,//礼包包含的商品兑换券
          };
        }
        this.objForm.goods_list.push(goods_item);
      }
    },
    isInGoods(ids) {
      //判断原来商品是否存在
      let itemx = "";
      if (this.temp_goods_list.length > 0) {
        this.temp_goods_list.forEach(function (item) {
          if (item.attribute_ids == ids) {
            itemx = item;
            return;
          }
        });
      }
      return itemx;
    },
    /**
     * 获取sku组合的名称
     **/
    getSkuName(sku_arr) {
      let that = this;
      let sku_obj = {};
      sku_arr.forEach(function (item) {
        let namearr = "";
        item += "";
        if (item.indexOf("_") > -1) {
          let strarr = item.split("_");
          strarr.forEach(function (e, i) {
            if (i >= strarr.length - 1) {
              namearr += that.attrIdName[e];
            } else {
              namearr += that.attrIdName[e] + "、";
            }
          });
        } else {
          namearr = that.attrIdName[item];
        }
        sku_obj[item] = namearr;
      });
      return sku_obj;
    },
    /**
     * 对商品属性进行SKU组合
     */
    doExchange(arr) {
      var len = arr.length;
      // 当数组大于等于2个的时候
      if (len >= 2) {
        // 第一个数组的长度
        var len1 = arr[0].length;
        // 第二个数组的长度
        var len2 = arr[1].length;
        // 2个数组产生的组合数
        var lenBoth = len1 * len2;
        //  申明一个新数组,做数据暂存
        var items = new Array(lenBoth);
        // 申明新数组的索引
        var index = 0;
        var i = 0;
        var j = 0;
        // 2层嵌套循环,将组合放到新数组中
        for (i = 0; i < len1; i++) {
          for (j = 0; j < len2; j++) {
            items[index] = arr[0][i] + "_" + arr[1][j];
            index++;
          }
        }
        // 将新组合的数组并到原数组中
        var newArr = new Array(len - 1);
        for (i = 2; i < arr.length; i++) {
          newArr[i - 1] = arr[i];
        }

        newArr[0] = items;
        // 执行回调
        return this.doExchange(newArr);
      } else {
        return arr[0];
      }
    },
    //获取上浮价格比例
    getGoUp(type_id) {
      let that = this;
      let go_up = 0;
      that.levelTree.forEach(item => {
        if (item.children) {
          if (go_up > 0) {
            return;
          }
          item.children.forEach(itemx => {
            if (parseInt(itemx.id) == parseInt(type_id)) {
              go_up = itemx.go_up;
              return;
            }
          })
        }
      })
      if (parseInt(go_up) == 0) {
        go_up = 15;
      }
      return go_up;
    }
  },
  created() {
    if (this.$route.params.id) {
      this.objForm.id = this.$route.params.id;
    }
    this.getLoadList();
  },
};
</script>

<style>
.el-cascader-menu__wrap {
  height: 550px;
}

.el-checkbox.is-bordered+.el-checkbox.is-bordered {
  margin-bottom: 10px;
  margin-left: 0;
  margin-right: 15px;
}

.el-checkbox.is-bordered {
  padding: 9px 10px 9px 10px;
}

.el-icon-close {
  color: red;
}

.line {
  width: 100%;
  height: 1px;
  background: #ccc;
  margin: 10px 0;
}
</style>